using System;
using System.Web;
using blog.BLL;
using blog.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using blog.Filter;
using Microsoft.AspNetCore.Authorization;


namespace blog.Controllers {
    public class BaseController : Controller {
        override public void OnActionExecuting(ActionExecutingContext context)
        {
            byte[] result;
            context.HttpContext.Session.TryGetValue("user_account", out result);
            if (result == null)
            {
                context.Result = new RedirectResult("/Login/Index");
                return;
            }
            string token;
            string token2;
            token = context.HttpContext.Session.GetString("access_token");
            context.HttpContext.Request.Cookies.TryGetValue("access_token", out token2);
            if (string.IsNullOrEmpty(token2) == true || token.Equals(token2) == false)
            {
                context.Result = new RedirectResult("/Login/Index");
                return;
            }

            base.OnActionExecuting(context);
        }
        public JsonResult result (object model = null, string msg = "", string code = ResultModel.CODE_SUCCESS) {
            ResultModel res = new ResultModel ();
            res.data = model;
            res.resultMsg = msg;
            res.resultCode = code;

            return Json (res);
        }
 
        protected void SetCookies(string key, string value, int minutes = 30)
        {
            HttpContext.Response.Cookies.Append(key, value, new CookieOptions
            {
                Expires = DateTime.Now.AddMinutes(minutes)
            });
        }

        protected void DeleteCookies(string key)
        {
            HttpContext.Response.Cookies.Delete(key);
        }

        protected string GetCookies(string key)
        {
            HttpContext.Request.Cookies.TryGetValue(key, out string value);
            if (string.IsNullOrEmpty(value))
                value = string.Empty;
            return value;
        }
    }
}